/**
 * jqGrid模块所需脚本
 * 作者：greedwind 
 * 日期：2018-10-23
 */


	//js/css插件包定义
    var bundles = {
		'export2pdf': ['/static/js/plugins/pdfmake/pdfmake-0.1.36.min.js', 
			'/static/js/plugins/pdfmake/vfs_fonts-0.1.36.js'
		],
		'export2excel': ['/static/js/plugins/jszip/jszip.min.js'],
		'jqueryUI':['/static/css/plugins/jqGrid/jquery-ui.css',
			'/static/css/plugins/jqGrid/ui.multiselect.css',
			'/static/js/plugins/jqGrid/jquery-ui.min.js',
			],
	};
	
    /**
     * 模拟require.js，用于避免变量或风格污染。
     * @param bundleIds
     * @param callbackFn
     * @returns
     */
	function require(bundleIds, callbackFn) {
		bundleIds.forEach(function(bundleId) {
		  if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
		});
		loadjs.ready(bundleIds, callbackFn);
	}
	
	/**
	 * 日期选择器，多用于jqgrid的searchoptions
	 * @param element
	 * @returns
	 */
    function datePick(element) {
		laydate.render({
			  elem: element //指定元素
		});
	}
    
    /**
     * 显示隐藏jqgrid过滤器行
     * @returns
     */
	function filterToolbar(){
		$("tr.ui-search-toolbar").toggle();
	}

	/**
	 * 将 “值1:描述1;值2:描述2” 格式的字串转换为select2的数据格式
	 * @param str
	 * @returns
	 */
	function var2Select2Data(str){
		str = str.trim() == "" ? ":;" : ":;" + str;
		var items = str.split(";");
		var data = new Array();
		for (i=0; i < items.length; i++ ){
			var item = items[i].split(":");
			var row = {};
			row.id = item[0];
			row.text = item[1];
			data.push(row);
		}
		return data;
	}
	/**
	 * 导出Excel
	 */
	function Export2Excel(obj) {
		params = obj.jqGrid('getGridParam','postData');		//GRID的查询条件
		colModel = obj.jqGrid('getGridParam', 'colModel')	//列设置
		var postData = {};
		//重构postData
		var rows = new Array();
	    for(var index in colModel) {
	        if (!colModel[index]["hidden"] 
	        	&& colModel[index]["name"] != '_act_')	//操作按钮列
	        {
	        	var row = {};
	        	row.label = colModel[index]["label"];
	        	row.name = colModel[index]["name"];
	        	row.width = colModel[index]["width"];
	        	row.hidden = colModel[index]["hidden"];
	            rows.push(row);        
	        }
	    };
	    
	    postData.title = obj.jqGrid('getGridParam','caption');
	    postData._search = params._search;
	    postData.nd = params.nd;
	    postData.rows = params.rows;
	    postData.page = params.page;
	    postData.sidx = params.sidx;
	    postData.filters = params.filters;
	    postData.colModel = rows;
	    
	    $("#export2excel_params").val(JSON.stringify(postData));
	    $("#export2excel").submit();
	};	
	
    /**
     * 列选择器 
     * @param grid	jqgrid对象
     * @returns
     */
	function columnSelector(grid){
	   	require(['jqueryUI'], function() {
	    	try{
	    		//jqgrid的columnChooser核bootstrap不太兼容
	    		grid.jqGrid('columnChooser',{
		            width: 550, 
		            dialog_opts: {
		                modal: true,
		                minWidth: 300,
		                height: 400,
		                show: 'blind',
		                hide: 'explode',
		                dividerLocation: 0.5
		            },
					done: function (perm) {
						if (perm) {
							// "OK" button are clicked
							this.jqGrid("remapColumns", perm, true);
							this.jqGrid("setGridWidth",$(window).width());
							$(this.jqGrid('getGridParam', 'pager')).css("width",$(window).width());
							saveColState(this);
						} else {
							// we can do some action in case of "Cancel" button clicked
						}
					}    		
		        });
	    	} catch (err){
	    		//console.log(err);
	    	}
		});
	}
	
	/*
	保存表格状态
	*/
	function saveColState(grid){
		myColModel = grid.jqGrid('getGridParam', 'colModel')	//列设置
		var setting = {};
		var rows = new Array();
	    for(var index in myColModel) {
			var row = {};
			row.label = myColModel[index]["label"];
			row.name = myColModel[index]["name"];
			row.width = myColModel[index]["width"];
			row.hidden = myColModel[index]["hidden"];
			row.resizable = myColModel[index]["resizable"];
			rows.push(row);
	    };
	    setting.colModle = rows;
		localStorage.setItem("jqGrid_" + grid.selector.replace(/[^a-zA-Z0-9_-]/g,""), JSON.stringify(setting));
	}
	
	/*
	还原表格状态(按调整的宽度和分辨率大小自动按百分比扩展)
	（有些许BUG, 待改良）
	*/
	function loadColState(grid){
		var setting = eval('(' + localStorage.getItem("jqGrid_" + grid.selector.replace(/[^a-zA-Z0-9_-]/g,"")) + ')');
		if (setting != null && typeof(setting.colModle) != 'undefined') {
			var myColModle = setting.colModle;
			var fixedWidth = 0;
			var totalWidth = 0;
			for(var index in myColModle){
				var awidth =  parseInt(myColModle[index]['width']);
				if (!myColModle[index]['hidden']){
					totalWidth = totalWidth + awidth;
				}
			}
			var qwidth = 0; 
			for(var index in myColModle){
				if (!myColModle[index]['hidden']){
	  				var iwidth = ($(window).width() - 52) *  parseFloat(myColModle[index]['width'])/totalWidth;
	  				if (typeof( myColModle[index]['name'].resizable != 'undefined')){
		  				grid.jqGrid('resizeColumn',  myColModle[index]['name'], iwidth);
	  				}
				}
	  			if (myColModle[index]['hidden']){
	  	  			grid.setGridParam().hideCol(myColModle[index]['name']);
	  			} else {
	  	  			grid.setGridParam().showCol(myColModle[index]['name']);
	  			}
			}
			grid.setGridWidth($(window).width()-50);
			grid.setGridParam().trigger("reloadGrid");
		}
	}
	
